﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using WorldmeServer.Models.Base;
using WorldmeServer.Models.用户相关;

namespace WorldmeServer.Utils
{
    public class JwtUtils
    {
        /// <summary>
        /// 颁发token
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="days">有效期</param>
        /// <returns></returns>
        public static string GenerateToken(User user, int days = 1)
        {
            string t = string.Empty;
            try
            {
                var claims = new[]
                {
                new Claim("User",JsonSerializer.Serialize(user))
            };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Constant.JWT_SECURITY_KEY));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    issuer: "Worldme",
                    audience: user.UserName,
                    claims: claims,
                    expires: DateTime.Now.AddDays(days),
                    signingCredentials: creds
                    );
                t = new JwtSecurityTokenHandler().WriteToken(token);
            }
            catch (Exception)
            {
                throw new Exception("Token生成失败，请联系管理员");
            }
            return t;
        }

    }
}
